package utility_jwt

import (
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

// GenerateToken generates a JWT token
func GenerateToken(ctx context.Context, userInfo entity.SysUser) (string, string, error) {
	expireTime := time.Now().Add(g.Cfg().MustGet(ctx, "jwt.expire").Duration())
	// Create claims with user information
	claims := &JWTClaims{
		UserInfo: userInfo,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expireTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    g.Cfg().MustGet(ctx, "jwt.issuer").String(),
			Subject:   g.Cfg().MustGet(ctx, "jwt.subject").String(),
			Audience:  g.Cfg().MustGet(ctx, "jwt.audience").Strings(),
		},
	}
	// Generate token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString(g.Cfg().MustGet(ctx, "jwt.secret").Bytes())
	if err != nil {
		return "", "", gerror.New("Failed to generate token")
	}
	return expireTime.String(), signedToken, nil
}
